/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.zcgl.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.zcgl.ZcglCompetitionPost;
import com.plian.system.mapper.zcgl.ZcglCompetitionPostMapper;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.service.yth.IWorkReportService;
import com.plian.system.service.zcgl.IZcglCompetitionPostService;
import com.plian.system.vo.zcgl.ZcglCompetitionPostVO;
import com.plian.system.wrapper.zcgl.ZcglCompetitionPostWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 中层管理人员管理 竞争上岗 服务实现类
 *
 * @author zsk
 * @since 2025-02-11
 */
@Slf4j
@Service
@AllArgsConstructor
public class ZcglCompetitionPostServiceImpl extends BaseServiceImpl<ZcglCompetitionPostMapper, ZcglCompetitionPost> implements IZcglCompetitionPostService, BaseFlowService {

    private FileService fileService;

    private FormWorkflowService formWorkflowService;

    private IFormCodeService formCodeService;

    private ZcglCompetitionPostWrapper zcglCompetitionPostWrapper;

    private IWorkReportService workReportService;

    private IOrgService orgService;

    private ISysUserService userService;

    @Override
    public boolean saveOrUpdate(ZcglCompetitionPost competitionPost) {
        boolean flag = false;
        if (competitionPost.getId() == null){
            flag = true;
            competitionPost.setCode(formCodeService.getCode(FormTypeConstant.ZCGLR_COMPETITION_POST_FORM));
            competitionPost.setFormType(String.valueOf(FormTypeConstant.ZCGLR_COMPETITION_POST_FORM));
        }

        boolean result = super.saveOrUpdate(competitionPost);
        if (flag){
            fileService.saveAll(String.valueOf(competitionPost.getId()), competitionPost.getDocList());
        }else {
            fileService.edit(String.valueOf(competitionPost.getId()), competitionPost.getDocList());
        }

        return result;
    }

    @Override
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            ZcglCompetitionPost competitionPost = getById(id);
            if (competitionPost == null) {
                return false;
            } else if (competitionPost.getStatus() != null &&
                    (competitionPost.getStatus() != FormStatusConstant.STASH && competitionPost.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }
        boolean result = super.deleteLogic(ids);
        return result;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        /**
         * 设置审批人和审批时间
         */
        ZcglCompetitionPost competitionPost = getById(id);
        competitionPost.setApprovedUser(TokenUtil.getTokenUserId());
        Date now = DateUtil.now();
        competitionPost.setApprovedTime(now);
        updateById(competitionPost);

        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        List<ZcglCompetitionPost> competitionPosts = list(new LambdaQueryWrapper<ZcglCompetitionPost>().in(ZcglCompetitionPost::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA))));
        List<ZcglCompetitionPostVO> competitionPostVOS = zcglCompetitionPostWrapper.entityToVO(competitionPosts);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(competitionPostVOS)){
                for (ZcglCompetitionPostVO vo : competitionPostVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getReportCompanyName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getReportCompanyId());
                    pd.put("formType", FormTypeConstant.ZCGLR_COMPETITION_POST_FORM);
                    pd.put("orgName", vo.getReportCompanyName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.ZCGLR_COMPETITION_POST_FORM);
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }


    /**
     * 统一处理状态机事件方法
     * @param id 主键
     * @param updateStatus 更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            ZcglCompetitionPost competitionPost = getById(id);
            competitionPost.setStatus(updateStatus);
            updateById(competitionPost);
            return true;
        } catch (Exception e) {
           log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    @Override
    public boolean submit(ZcglCompetitionPost competitionPost) {
        if (!Optional.ofNullable(competitionPost.getStatus()).isPresent()){
            competitionPost.setStatus(FormStatusConstant.UNREVIEWED);
        }

        boolean result = saveOrUpdate(competitionPost);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(String.valueOf(competitionPost.getId()), competitionPost.getFormType(),processVariable);
        return result;
    }
}
